package com.authentication.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.DeferredSecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.access.intercept.AuthorizationFilter;
import org.springframework.security.web.context.SecurityContextHolderFilter;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 *
 * 通过组合 使用 {@link SecurityContextHolderFilter} 和 {@link AuthorizationFilter} 替换了此过滤器的功能
 */
@Deprecated
public class SecurityContextRepositoryAuthenticationFilter extends OncePerRequestFilter {

    private final SecurityContextRepository securityContextRepository;

    public SecurityContextRepositoryAuthenticationFilter(SecurityContextRepository securityContextRepository) {
        this.securityContextRepository = securityContextRepository;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        DeferredSecurityContext deferredSecurityContext = securityContextRepository.loadDeferredContext(request);
        Authentication authentication = deferredSecurityContext.get().getAuthentication();
        if (authentication == null) {
            throw new AuthenticationCredentialsNotFoundException("未找到登陆凭证");
        }
        SecurityContextHolder.getContext().setAuthentication(authentication);

        filterChain.doFilter(request, response);
    }
}
